<template>
  <view class="transport-address mt-10px mb-12px">
    <view class="flex justify-between items-center mb-14px">
      <view class="flex items-center">
        <text class="text-grey2 mr-8px text-default">
          {{ address.value.name || "添加收货地址" }}
        </text>
        <text class="text-s text-999">{{ address.value.phone }}</text>
      </view>
      <text class="text-primary text-s" @click.stop="handleChangeAddress"
        >更改地址</text
      >
    </view>
    <view class="text-s text-grey2 leading-none">{{
      address.value.detail
    }}</view>
  </view>
  <view class="order-goods mb-12px">
    <view
      class="goods-cover cover w-80px h-80px"
      :style="{ backgroundImage: `url(${info.productInfo.productImageUrl})` }"
    ></view>
    <view
      class="flex-1 flex flex-col leading-none flex-col px-12px h-80px py-2px"
      style="box-sizing: border-box"
    >
      <view class="text-goods text-base flex-1">{{
        info.productInfo.productName || "-"
      }}</view>
      <text class="text-s text-999">{{
        skuLabel(info.productInfo.productSkuSpData) || "-"
      }}</text>
      <view class="mt-12px text-base flex items-end text-primary text-17px">
        <image
          class="mr-8px w-17px h-20px"
          :src="ossImg('others/goods/oreo.png')"
        />
        {{ info.productInfo.score }} 小饼干
      </view>
    </view>
    <text class="text-base text-999">共{{ form.quantity }}件</text>
  </view>
  <view class="mb-12px bg-w px-20px py-10px">
    <label class="text-s text-666 leading-none">买家留言</label>
    <textarea
      v-model="form.note"
      class="w-full h-80px text-base"
      style="padding: 20px 7px; box-sizing: border-box"
      :rows="1"
      :maxlength="100"
      placeholder-style="font-size: 14px;"
      placeholder="选填，您可以在这里为商家留言,最多不超过100字"
    />
  </view>
  <oreo-cell
    label="支付方式"
    :label-style="{ color: '#0D0D0D', fontSize: '14px' }"
    :arrow="false"
  >
    <template v-slot:suffix>
      <text class="text-base mr-13px">积分</text>
    </template>
  </oreo-cell>
  <view class="h-12px"></view>
  <oreo-cell
    label="优惠券"
    :label-style="{ color: '#0D0D0D', fontSize: '14px' }"
  >
    <view class="flex flex-1 justify-between pr-24px items-center">
      <view class="coupon-status">无可用</view>
      <view>未使用</view>
    </view>
  </oreo-cell>
  <view class="order-action">
    <view class="flex-1 text-base px-16px">
      合计：<text class="text-primary font-bold"
        >{{ info.totalScore || "0" }}积分</text
      >
    </view>
    <button @click.stop="onCreate">提交订单</button>
  </view>

  
</template>

<script setup>
import { reactive, ref } from "vue";
import { CreateBiscuitOrder, GetBiscuitSettle } from "@/services/biscuit";
import { onLoad, onShow, onUnload, onHide } from "@dcloudio/uni-app";
import { message, ossImg, debounce } from "@/utils/utils";
import OreoCell from "@/components/oreo-cell";
import privacyPopup from "@/components/privacy-popup";

let enterTime = "";
let outTime = "";
let stayTime = "";

const info = ref({ productInfo: {} });

const address = reactive({
  value: {
    name: "",
    phone: "",
    detail: "",
  },
});
const form = reactive({
  quantity: 1,
  addressId: "",
  note: "",
});

onLoad((option) => {
  if (option.productSkuId) Object.assign(form, option);
  getInfo(option);
});

onShow(async () => {
  // 用户进入时间
  enterTime = new Date();
  // choose address callback
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  console.log(currentPage);
  if (currentPage.data.hasOwnProperty("addressInfo")) {
    address.value = currentPage.data.addressInfo;
    form.addressId = currentPage.data.addressId;
    console.log(address.value, form);
  }
  getApp().accessLogAdd();
});

onHide(() => {
  // 用户退出时间
  outTime = new Date();
  //停留时间(毫秒)
  stayTime = (outTime.getTime() - enterTime.getTime()) / 1000;
  getApp().emdlz(
    "track",
    "event",
    "points_store_page",
    "view",
    "order_detail_page",
    stayTime
  );
});

onUnload(() => {
  // 用户退出时间
  outTime = new Date();
  //停留时间(毫秒)
  stayTime = (outTime.getTime() - enterTime.getTime()) / 1000;
  getApp().emdlz(
    "track",
    "event",
    "points_store_page",
    "view",
    "order_detail_page",
    stayTime
  );
});

const getInfo = async (params) => {
  const { data } = await GetBiscuitSettle(params);
  info.value = data;
  const defaultAddress = data.addresses.find((item) => item.defaultFlag);
  console.log(defaultAddress);
  if (defaultAddress) {
    form.addressId = defaultAddress.id;
    const obj = {
      ...defaultAddress,
      detail: addressDetail(defaultAddress),
    };
    address.value = obj;
  }
  console.log(data);
};

const addressDetail = ({ province, city, region, detailAddress }) => {
  return province + city + region + detailAddress;
};

const onCreate = debounce(
  async () => {
    getApp(info.totalScore).emdlz(
      "track",
      "event",
      "points_store_page",
      "click",
      "order_pay",
      info.value.totalScore
    );

    if (address.value.detail === "") return message("地址不能为空！");

    const res = await CreateBiscuitOrder({
      ...form,
      quantity: +form.quantity,
    });
    // to do...
    if (res?.code === 200) {
      await message("提交订单成功", 1000);
      uni.redirectTo({ url: `/personalPages/order/index?type=2` });
    }
  },
  500,
  false
);

const handleChangeAddress = () => {
  getApp().emdlz(
    "track",
    "event",
    "points_store_page",
    "click",
    "address_change",
    ""
  );

  uni.navigateTo({
    url: "/pages/address/address?choose=1",
  });
};

const skuLabel = (skuData) => {
  return skuData.map(({ value, key }) => `${key}${value}`).join(" ");
};
</script>

<style lang="less" scoped>
@import "@/static/css/theme.less";

.order-action {
  width: 100%;
  display: flex;
  align-items: center;
  background-color: white;
  position: fixed;
  bottom: 0;
  left: 0;

  button {
    width: 140px;
    height: 56px;
    line-height: 56px;
    border-radius: 0;
    background-color: @primary-color;
    color: white;
    font-size: 16px;
  }
}

.coupon-status {
  width: 64px;
  height: 28px;
  background: #ffffff;
  border: 1px solid @primary-color;
  border-radius: 14px;
  box-sizing: border-box;
  font-size: 14px;
  font-weight: 400;
  color: @primary-color;
  line-height: 28px;
  text-align: center;
}

.transport-address {
  padding: 14px 20px;
  box-sizing: border-box;
  background-color: white;
  line-height: 1;
}

.order-goods {
  display: flex;
  align-items: flex-end;
  padding: 12px 29px 12px 20px;
  box-sizing: border-box;
  background: white;
}
</style>
